package com.javayz.fileuploadanddownload.service.Impl;
import com.javayz.fileuploadanddownload.entity.Files;
import com.javayz.fileuploadanddownload.entity.all;
import com.javayz.fileuploadanddownload.mapper.FileMapper;
import com.javayz.fileuploadanddownload.response.ResponseCode;
import com.javayz.fileuploadanddownload.response.Result;
import com.javayz.fileuploadanddownload.service.FileService;
import com.javayz.fileuploadanddownload.util.ZipUtils;
import com.javayz.fileuploadanddownload.util.deleteFileUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


/**
 * @author by:
 * @ClassName: FileServiceImpl
 * @Description: TODO
 * @Date:
 */
@Service
public class FileServiceImpl implements FileService {
    @Value("${file.save-path}")
    private String savePath;
    @Autowired
    private FileMapper fileMapper;

    private static final int  BUFFER_SIZE = 2*2048;

    /**
     *@描述：调用删除下载压缩方法
     *@参数： [dateFile, newFile, response]
     *@返回值： void
     *@创建人： ZLQ
     *@创建时间： 2022/11/10 14:39
     *@修改人和其它信息：
     */
    @Override
    public  void  deleteFile(String dateFile,File newFile, HttpServletResponse response) {

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(newFile+".zip");
            if (newFile.exists()){
                //调用压缩方法
                ZipUtils.toZip(dateFile, fos,true);
                //调用下载方法
                ZipUtils.downFile(response, newFile+".zip");
            }

            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {//是否压缩或下载成功都会调用
            //清空占用线程 不清空无法删除
            System.gc();
            //调用删除文件夹方法
            ZipUtils.deleteDir(new File(dateFile));
            //调用删除压缩包方法
            ZipUtils.deleteFile(dateFile+".zip");
        }

    }

    /**
     *@描述：获取文件并写入到新文件夹方法
     *@参数： [files, dateFile]
     *@返回值： void
     *@创建人： ZLQ
     *@创建时间： 2022/11/10 14:38
     *@修改人和其它信息：
     */
    @Override
    public void inputStream(Files files , String dateUrl){

        FileOutputStream outputStream = null;
        FileInputStream inputStream = null;
        String urlFile = null;
        try {
            //准备压缩的文件夹
            File file = new File(dateUrl);
            if (!file.exists()) {
                //如果不存在创建文件夹
                file.mkdirs();
            }
            //目标文件夹和文件名称
            urlFile = dateUrl+"/"+files.getFileName();
            //目标路径
            outputStream = new FileOutputStream(new File(urlFile));
            //获取源文件
            inputStream = new FileInputStream(files.getFilePath()+"/"+files.getFileName());
            byte[] bytes = new byte[BUFFER_SIZE];
            int num = 0;
            //写入文件
            while ((num = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, num);
                outputStream.flush();
            }
            if (inputStream != null){
                inputStream.close();
            }
            if (outputStream != null){
                outputStream.close();
            }
        } catch (FileNotFoundException e) {
         deleteFileUtils.fileCloseDelete(inputStream, outputStream, dateUrl);
            // e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null){
                    inputStream.close();
                }
                if (outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Result upLoadFiles(MultipartFile file, String newFileName, String[] sourcePk, String[] tableName,String tableFileName) {

        String fileSuffix = null;
        long MAX_SIZE = Long.MAX_VALUE;
        String fileName = file.getOriginalFilename();//文件名
        if (StringUtils.isEmpty(fileName)) {
            return new Result(ResponseCode.FILE_NAME_EMPTY.getCode(), ResponseCode.FILE_NAME_EMPTY.getMsg(), null);
        }
        if (file.getSize() > MAX_SIZE) {
            return new Result(ResponseCode.FILE_MAX_SIZE.getCode(), ResponseCode.FILE_MAX_SIZE.getMsg(), null);
        }
        String suffixName = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".")) : null;
        List<Files> filesList = new ArrayList<>();
        for (int i = 0; i < sourcePk.length; i++) {
            String uuid = null;
            //newFileName用户传入文件名称/
            String newPath = savePath +"/"+tableFileName + "/" + newFileName +"/"+sourcePk[i];
            File newFile = new File(newPath, fileName);
            if (!newFile.getParentFile().exists()) {
                //如果不存在创建文件夹
                newFile.getParentFile().mkdirs();
            }
            try {
                //文件写入
                FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);

            } catch (IOException e) {
                e.printStackTrace();
            }
            Files files = fileMapper.selectFileSourcePk(newPath, fileName, sourcePk[i], tableName[i]);
            uuid = UUID.randomUUID().toString().replace("-","");
            if ( files == null) {
                filesList = new ArrayList<>();
                filesList.add(new Files(null, newPath, fileName, suffixName, null, sourcePk[i], tableName[i],uuid));
                try {
                    fileMapper.insertFile(filesList);
                    fileSuffix  = fileMapper.fileSuffixStr(sourcePk[i],fileName);
                    ZipUtils.FixFileName(newFile.toString(),newPath+"/"+ uuid+fileSuffix);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return new Result(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), "数据上传成功");
    }

    /**
     *@描述：获取当前指定id的数据
     *@参数： [id]
     *@返回值： java.util.List<com.javayz.fileuploadanddownload.entity.Files>
     *@创建人： ZLQ
     *@创建时间： 2022/11/18 15:31
     *@修改人和其它信息：
     */
    @Override
    public List<Files> getFileById(String[] id) {
        List<Files> files =new ArrayList<>();
        files = fileMapper.selectFileById(id);
        return files;
    }

    /**
     *@描述：获取指定包下的子包
     *@参数： [tableName]
     *@返回值： java.util.List<java.lang.String>
     *@创建人： ZLQ
     *@创建时间： 2022/12/29 9:14
     *@修改人和其它信息：
     */
    @Override
    public List<String> fileAll(String tableName) {

        File file = new File(savePath+"/"+tableName);
        File[] fileList = file.listFiles();
        List<String> list = new ArrayList<>();
        if(list == null){
            return list ;
        }
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isDirectory()) {//判断是否为一个目录
                String fileNames = fileList[i].getName();//获取文件名
                list.add(fileNames);
            }
        }
        return  list ;
    }


    @Override
    public List<String> selectAll(String sourcePk,String tableName,String filePathName ) {
        return fileMapper.selectAll(sourcePk,tableName ,filePathName);
    }

    @Override
    public List<String> queryLists(String[] sourcePk) {
        return fileMapper.queryLists(sourcePk);
    }

    @Override
    public List<String> queryTableGcjsgl(String[] sourcePk) {
        return fileMapper.queryTableGcjsgl(sourcePk);
    }

    @Override
    public List<String> queryTableGcjbxx(String[] sourcePk) {
        return fileMapper.queryTableGcjbxx(sourcePk);
    }

    @Override
    public List<String> queryTableJhcbbz(String[] urlFile) {
        return fileMapper.queryTableJhcbbz(urlFile);
    }

    @Override
    public List<String> queryTableJscbbz(String[] sourcePk) {
        return fileMapper.queryTableJscbbz(sourcePk);
    }

    @Override
    public List<String> queryTableSgkjxy(String[] sourcePk) {
        return fileMapper.queryTableSgkjxy(sourcePk);
    }

    @Override
    public List<String> queryTableSrfpdj(String[] sourcePk) {
        return fileMapper.queryTableSrfpdj(sourcePk);
    }

    @Override
    public List<String> queryTableWxf(String[] sourcePk) {
        return fileMapper.queryTableWxf(sourcePk);
    }

    @Override
    public List<String> queryTableWxht(String[] sourcePk) {
        return fileMapper.queryTableWxht(sourcePk);
    }

    @Override
    public List<String> queryTableWxjh(String[] sourcePk) {
        return fileMapper.queryTableWxjh(sourcePk);
    }

    @Override
    public List<String> queryTableWxjs(String[] sourcePk) {
        return fileMapper.queryTableWxjs(sourcePk);
    }

    @Override
    public List<String> queryTableWxkjxy(String[] sourcePk) {
        return fileMapper.queryTableWxkjxy(sourcePk);
    }

    @Override
    public List<String> queryTableXsht(String[] sourcePk) {
        return fileMapper.queryTableXsht(sourcePk);
    }

    @Override
    public String selectAllTable(String tableName) {
        return fileMapper.selectAllTable(tableName);
    }

    @Override
    public void insertwxkjxy(all a){
        fileMapper.insertWxkjxy(a);
    };

    @Override
    public void insertXsht(all a){
        fileMapper.insertXsht(a);
    };

    @Override
    public void insertGcjbxx(all a){
        fileMapper.insertGcjbxx(a);
    };

    @Override
    public void insertJhcbbz(all a){
        fileMapper.insertJhcbbz(a);
    };

    @Override
    public void insertSgkjxy(all a){
        fileMapper.insertSgkjxy(a);
    };

    @Override
    public void insertGcjsgl(all a){
        fileMapper.insertGcjsgl(a);
    };

    @Override
    public void insertJscbbz(all a){
        fileMapper.insertJscbbz(a);
    };

    @Override
    public void insertWxjh(all a){
        fileMapper.insertWxjh(a);
    };

    @Override
    public void insertWxjs(all a){
        fileMapper.insertWxjs(a);
    };

    @Override
    public void insertSrfpdj(all a){
        fileMapper.insertSrfpdj(a);
    };

    @Override
    public void insertWxf(all a){
        fileMapper.insertWxf(a);
    };

    @Override
    public void insertWxht(all a){
        fileMapper.insertWxht(a);
    }

    @Override
    public void deleteWxkjxy(String source_pk) {
        fileMapper.deleteWxkjxy(source_pk);
    }

    @Override
    public void deleteWxht(String source_pk) {
        fileMapper.deleteWxht(source_pk);
    }

    @Override
    public void deleteGcjbxx(String source_pk) {
        fileMapper.deleteGcjbxx(source_pk);
    }

    @Override
    public void deleteSgkjxy(String source_pk) {
        fileMapper.deleteSgkjxy(source_pk);
    }

    @Override
    public void deleteJhcbbz(String source_pk) {
        fileMapper.deleteJhcbbz(source_pk);
    }

    @Override
    public void deleteGcjsgl(String source_pk) {
        fileMapper.deleteGcjsgl(source_pk);
    }

    @Override
    public void deleteJscbbz(String source_pk) {
        fileMapper.deleteJscbbz(source_pk);
    }

    @Override
    public void deleteWxjh(String source_pk) {
        fileMapper.deleteWxjh(source_pk);
    }

    @Override
    public void deleteWxjs(String source_pk) {
        fileMapper.deleteWxjs(source_pk);
    }

    @Override
    public void deleteSrfpdj(String source_pk) {
        fileMapper.deleteSrfpdj(source_pk);
    }

    @Override
    public void deleteWxf(String source_pk) {
        fileMapper.deleteWxf(source_pk);
    }

    @Override
    public void deleteXsht(String source_pk) {
        fileMapper.deleteXsht(source_pk);
    }

    @Override
    public String selectTableName(String sourcePk) {
       String tableName =  fileMapper.selectTableName(sourcePk);
        return  tableName;
    }

    @Override
    public all selectEngineeringNo(String tableName,String sourcePk) {
      all all  =  fileMapper.selectEngineeringNo(tableName, sourcePk);
        return all;
    }

    @Override
    public List<String> selectPathName(String sourcePk) {
        return fileMapper.selectPathName(sourcePk);
    }

    @Override
    public Files selectVbillstatus(String id) {
       return fileMapper.selectVbillstatus(id);
    }

    @Override
    public void deleteVbillstatus(String id) {
        fileMapper.deleteVbillstatus(id);
    }

    @Override
    public all selectVbillstatuIds(String tableName ,String sourcePk) {
       return fileMapper.selectVbillstatuIds(tableName , sourcePk);
    }


}
